package com.example.clientsideapplication;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class UsersStatisticsService extends IntentService {

	private Socket socket;
	private String serverAddress;
	private int serverSocket;
	private ObjectInputStream inputStream;
	private ObjectOutputStream outputStream;
	private DataPackage outputMessage;
	private DataPackage inputMessage;
	private final static String MY_PREFERENCES = "myAppPref";

	public UsersStatisticsService() {
		super("UsersStatisticsService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		serverAddress = intent.getStringExtra("serverAddress");
		serverSocket = intent.getIntExtra("serverSocket", 21111);

		try {
			socket = new Socket(serverAddress, serverSocket);
			inputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
			outputStream = new ObjectOutputStream(socket.getOutputStream());

			outputMessage = new DataPackage(8, true);
			outputStream.writeObject(outputMessage);

			inputMessage = (DataPackage) inputStream.readObject();
			
			boolean updated = (Boolean)inputMessage.getDataPackage();
			
			SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = prefs.edit();

			editor.putBoolean("firstOpening", !updated);

			editor.commit();
			
			socket.close();
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
